<template>
  <ContentWrap>
    <el-form :model="queryParams" ref="queryFormRef" label-width="auto" :inline="true">
      <el-form-item label="客户编号" prop="customerNo">
        <el-input v-model="queryParams.customerNo" placeholder="请输入客户编号" :clearable="true" />
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入名称" :clearable="true" />
      </el-form-item>
      <el-form-item>
        <el-button v-hasPermi="['customer:customer:list']" @click="handleClickSearch">
          <Icon icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="handleClickReset">
          <Icon icon="ep:refresh" />
          重置
        </el-button>
        <el-button v-hasPermi="['customer:customer:create']" @click="handleClickCreate">
          <Icon icon="ep:plus" />
          新增
        </el-button>
        <el-button v-hasPermi="['customer:customer:import']" @click="handleClickImport">
          <Icon icon="ep:upload" />
          导入
        </el-button>
        <el-button v-hasPermi="['customer:customer:sendMail']" @click="handleClickSendMail">
          发邮件
        </el-button>
        <el-button v-hasPermi="['customer:customer:market']" @click="handleClickMarket">
          一键营销
        </el-button>
        <el-button
          @click="handleClickRecycle"
          v-hasPermi="['customer:customer:recycleList']"
          :style="queryParams.isRecycle ? 'color:#E6A23C' : ''"
        >
          {{ recycleMessage }}
        </el-button>
      </el-form-item>
    </el-form>
    <Table
      ref="tableRef"
      :columns="columns"
      :page-param="queryParams"
      :adaptive="true"
      :page-data="queryData"
      save-key="customer"
      height-per="90"
      @page-change="getPage"
      @row-dblclick="handleTableDblclick"
      @row-click="handleTableClick"
    >
      <template #mainImageUrl="{ row }">
        <span v-if="row.images.length == 0"></span>
        <el-image
          v-else
          preview-teleported
          loading="lazy"
          :src="row.images[0].url"
          :preview-src-list="[row.images[0].url]"
          fit="cover"
          class="w-[100px] h-[100px]"
        />
      </template>
      <template #menu="{ row }">
        <context-menu-item
          label="修改"
          @click="handleMenuUpdate(row)"
          v-hasPermi="['customer:customer:update']"
        />
        <context-menu-item
          label="放入回收站"
          @click="handleMenuSetRecycle(row)"
          v-hasPermi="['customer:customer:setRecycle']"
          v-if="queryParams.isRecycle == false"
        />
        <context-menu-item
          label="恢复"
          @click="handleMenuRecyleRestore(row)"
          v-hasPermi="['customer:customer:recyleRestore']"
          v-if="queryParams.isRecycle == true"
        />
        <context-menu-item
          label="彻底删除"
          @click="handleMenuDeleted(row)"
          v-hasPermi="['customer:customer:deleted']"
          v-if="queryParams.isRecycle == true"
        />
        <context-menu-item
          label="新增跟进"
          @click="handleMenuCreateFollow(row)"
          v-hasPermi="['customer:customer:createFollow']"
        />
        <context-menu-item
          label="放入公海"
          @click="handleMenuPutInPool(row)"
          v-hasPermi="['customer:customer:putInPool']"
        />
        <context-menu-item
          label="客户移交"
          @click="handleMenuTransfer(row)"
          v-hasPermi="['customer:customer:transfer']"
        />
        <context-menu-item
          label="发邮件"
          @click="handleMenuSendMail(row)"
          v-hasPermi="['customer:customer:sendMail']"
        />
        <context-menu-item
          label="一键营销"
          @click="handleMenuMarket(row)"
          v-hasPermi="['customer:customer:market']"
        />
      </template>
    </Table>
  </ContentWrap>
  <CustomerEdit ref="editRef" @success="handleEditSuccess" />
  <CustomerShow ref="showRef" />
  <CustomerPutInPoolReason ref="putInPoolReasonRef" @success="getPage()" />
  <CustomerCreateFollow ref="createFollowRef" @success="getPage()" />
  <MailMarketSelect ref="marketSelectRef" @success="getPage()" />
  <CustomerTranser ref="transferRef" @success="getPage()" />
  <CustomerContactMailSelect ref="contactSelectRef" />
  <CustomerSendMailSelect ref="sendMailSelectRef" />
</template>
<script setup name="Customer" lang="ts">
import CustomerEdit from '@/views/customer/customer/CustomerEdit.vue'
import CustomerShow from '@/views/customer/customer/CustomerShow.vue'
import CustomerPutInPoolReason from './CustomerPutInPoolReason.vue'
import CustomerCreateFollow from './CustomerCreateFollow.vue'
import MailMarketSelect from '@/views/market/mailMarket/MailMarketSelect.vue'
import CustomerContactMailSelect from '@/views/customer/customer/CustomerContactMailSelect.vue'
import CustomerSendMailSelect from '@/views/customer/customer/CustomerSendMailSelect.vue'
import CustomerTranser from '@/views/customer/customer/CustomerTranser.vue'

import * as CustomerApi from '@/api/customer/customer'
import * as RoleApi from '@/api/system/role/role'

import { SettingBusinessModuleEnum } from '@/utils/constants'
import { getKeyList } from '@pureadmin/utils'
import { getBussinessModule } from '@/views/setting/businessField/BusinessFieldUtil'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { camelCase } from 'lodash-es'
import { useUserStore } from '@/store/modules/user'
const userStore = useUserStore()
const { wsCache } = useCache()
const message = useMessage() // 消息弹窗

const recycleMessage = ref('回收站')
const { push } = useRouter() // 路由

const contactSelectRef = ref()
const sendMailSelectRef = ref()
const tableRef = ref()
const editRef = ref()
const showRef = ref()
const transferRef = ref()
const putInPoolReasonRef = ref()
const createFollowRef = ref()
const marketSelectRef = ref()
const queryFormRef = ref()
const queryParams = ref({
  customerNo: undefined,
  name: undefined,
  source: undefined,
  grade: undefined,
  stage: undefined,
  state: undefined,
  isRecycle: false,
  isFallPool: false
})
const queryData = ref()

let columns = ref<any[]>([
  {
    label: '客户编号',
    prop: 'customerNo',
    minWidth: '140'
  }
])

/** 初始化 */
onMounted(() => {
  dataInit()
  getPage()
})

const dataInit = async () => {
  columns.value = [
    {
      type: 'selection',
      alignWhole: 'center'
    },
    {
      label: '客户编号',
      prop: 'customerNo',
      minWidth: '140'
    },
    {
      label: '名称',
      prop: 'name',
      minWidth: '240'
    },
    {
      label: '简称',
      prop: 'shortName',
      minWidth: '240'
    },
    {
      label: '公司主图片',
      prop: 'mainImageUrl',
      slot: 'mainImageUrl',
      minWidth: '140'
    },

    {
      label: '所属人',
      prop: 'owner.nickname',
      minWidth: '240'
    },

    {
      label: '所属部门',
      prop: 'dept.name',
      minWidth: '240'
    },
    {
      label: '国家',
      prop: 'country.name',
      minWidth: '240'
    },
    {
      label: '上次跟进时间',
      prop: 'lastFollowTime',
      minWidth: '240'
    },
    {
      label: '上次发邮件时间',
      prop: 'lastSendMailTime',
      minWidth: '240'
    },
    {
      label: '即将掉入公海',
      prop: 'comingFallPoolTime',
      minWidth: '240'
    }
  ]
  const roleColumns = await RoleApi.getColumnByRoleCodes({
    codes: wsCache.get(CACHE_KEY.USER).roles
  })

  const roleCustomerColumns = roleColumns
    .filter((column) => column.table.name == 'customer_info')
    .map((column) => camelCase(column.columnName))

  const roleCustomerContactColumns = roleColumns
    .filter((column) => column.table.name == 'customer_contact')
    .map((column) => camelCase(column.columnName))

  // 加载业务字段
  const customerModuleField = await getBussinessModule(SettingBusinessModuleEnum.CUSTOMER)

  customerModuleField.immutableFields.forEach((item) => {
    if (roleCustomerColumns.includes(item.fieldName)) return
    columns.value.push({
      label: item.showName,
      prop: item.fieldName,
      formatter: (row) =>
        row[item.fieldName] == 0
          ? ''
          : item.options.find((obj) => obj.id === row[item.fieldName])?.name
    })
  })
  customerModuleField.customFields.forEach((item) => {
    if (roleCustomerColumns.includes(item.fieldName)) return
    columns.value.push({
      label: item.showName,
      prop: item.fieldName
    })
  })
  columns.value = columns.value.concat([
    { label: '主联系人姓名', prop: 'mainContact.name' },
    { label: '主联系人昵称', prop: 'mainContact.nickName' },
    { label: '主联系人职位', prop: 'mainContact.position' }
  ])

  const contactModuleField = await getBussinessModule(SettingBusinessModuleEnum.CUSTOMER_CONTACT)
  contactModuleField.immutableFields.forEach((item) => {
    if (roleCustomerContactColumns.includes(item.fieldName)) return
    columns.value.push({
      label: '主联系人' + item.showName,
      prop: 'mainContact.' + item.fieldName,

      formatter: (row) =>
        row['mainContact'][item.fieldName] == 0
          ? ''
          : item.options.find((obj) => obj.id === row['mainContact'][item.fieldName])?.name
    })
  })

  contactModuleField.customFields.forEach((item) => {
    if (roleCustomerContactColumns.includes(item.fieldName)) return
    columns.value.push({
      label: '主联系人' + item.showName,
      prop: 'mainContact.' + item.fieldName
    })
  })

  columns.value = columns.value.concat([
    {
      label: '创建时间',
      prop: 'createTime'
    },
    {
      label: '上次修改时间',
      prop: 'updateTime'
    }
  ])

  recycleMessage.value = '回收站'
  queryParams.value = {
    customerNo: undefined,
    name: undefined,
    source: undefined,
    grade: undefined,
    stage: undefined,
    state: undefined,
    isRecycle: false,
    isFallPool: false
  }
}

/** 搜索按钮操作 */
const handleClickSearch = () => {
  getPage()
}

/** 重置按钮操作 */
const handleClickReset = () => {
  queryFormRef.value?.resetFields()
  handleClickSearch()
}

/** 新增按钮操作 */
const handleClickCreate = () => {
  editRef.value.open(0)
}

/** 处理响应事件  */
const getPage = async () => {
  queryData.value = await CustomerApi.pageQuery(queryParams.value)
}

const handleClickRecycle = () => {
  if (queryParams.value.isRecycle) {
    recycleMessage.value = '回收站'
    queryParams.value.isRecycle = false
  } else {
    recycleMessage.value = '返回列表'
    queryParams.value.isRecycle = true
  }
  getPage()
}

/** 处理table行双击事件 */
const handleTableDblclick = (row) => {
  editRef.value.open(row.id)
}

/** 处理右击事件 修改 */
const handleMenuUpdate = (row) => {
  editRef.value.open(row.id)
}

/** 处理右击事件 放入回收站 */
const handleMenuSetRecycle = async (row) => {
  const selectRows = getMultipleSelect(row)
  const rowIds: any[] = getKeyList(selectRows, 'id')
  await CustomerApi.setRecycle(rowIds)
  getPage()
  message.success('放入成功')
}

/** 处理右击事件 回收站-恢复 */
const handleMenuRecyleRestore = async (row) => {
  const selectRows = getMultipleSelect(row)
  const rowIds: any[] = getKeyList(selectRows, 'id')
  await CustomerApi.restore(rowIds)
  getPage()
  message.success('恢复成功')
}

/** 处理右击事件 回收站-彻底删除 */
const handleMenuDeleted = async (row) => {
  const selectRows = getMultipleSelect(row)
  const rowIds: any[] = getKeyList(selectRows, 'id')
  await CustomerApi.deleted(rowIds)
  getPage()
  message.success('彻底删除成功')
}

const getMultipleSelect = (row) => {
  let selectRows = tableRef.value.getTableRef().getSelectionRows()
  if (row != null && !selectRows.includes(row)) selectRows.push(row)
  return selectRows
}

const handleEditSuccess = () => {
  getPage()
}

const handleMenuCreateFollow = async (row) => {
  createFollowRef.value.open(row)
}

const handleMenuPutInPool = (row) => {
  const selectRows = getMultipleSelect(row)
  const rowIds: any[] = getKeyList(selectRows, 'id')
  putInPoolReasonRef.value.open(rowIds)
}

const handleMenuTransfer = async (row) => {
  transferRef.value.open({ id: row.id, ownerId: row.ownerId })
}

const handleClickImport = async () => {}

const handleClickSendMail = async () => {
  sendMail(null)
}

const handleClickMarket = async () => {
  customerMarket(null)
}

const handleMenuSendMail = async (row) => {
  sendMail(row)
}

const sendMail = async (row) => {
  const selectRows = getMultipleSelect(row)
  const rowIds: any[] = getKeyList(selectRows, 'id')
  if (rowIds.length == 0) {
    message.error('请选择客户')
    return
  }
  const mailInfos = await CustomerApi.getMailInfoByCustomerIds({ ids: [rowIds[0]] })
  if (mailInfos.length == 0) {
    await message.confirm('选择的客户没有邮件地址，确定要继续吗？')
    push({ name: 'MailEdit', state: { type: 'write' } })
  }
  if (mailInfos.length == 1) {
    push({
      name: 'MailEdit',
      state: {
        receivers: [{ name: mailInfos[0].contact.name, address: mailInfos[0].mailAddress }],
        userId: userStore.getUser.id,
        type: 'customerSend'
      }
    })
  } else {
    sendMailSelectRef.value.open({
      customerName: selectRows[0]['name'],
      mailInfos: mailInfos
    })
  }
}

const handleMenuMarket = async (row) => {
  customerMarket(row)
}

const customerMarket = async (row) => {
  const selectRows = getMultipleSelect(row)
  const rowIds: any[] = getKeyList(selectRows, 'id')
  if (rowIds.length == 0) {
    message.error('请选择客户')
    return
  }
  marketSelectRef.value.open(rowIds)
}

const handleTableClick = (row) => {
  showRef.value.open(row.id)
}
</script>
